package com.kkd.kkdapp.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

public class ListenBottomScrollView extends ScrollView {

	private boolean noMore = false;

	private OnScrollToBottomListener onScrollToBottomListener;

	public ListenBottomScrollView(Context context) {
		super(context);
	}

	public ListenBottomScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt) {
		// 此处为旧逻辑
		// if (onScrollToBottomListener != null) {
		// onScrollToBottomListener.onScroll(getScrollY());
		// }
		// View view = (View) getChildAt(getChildCount() - 1);
		// int d = view.getBottom();
		// d -= (getHeight() + getScrollY());
		// if (d == 0) {// 此处表示ScrollView滑动到底部
		// if (!noMore && onScrollToBottomListener != null)
		// onScrollToBottomListener.onScrollToBottom();
		// } else
		// super.onScrollChanged(l, t, oldl, oldt);
		if (onScrollToBottomListener != null) {
			onScrollToBottomListener.onScroll(getScrollY());
		}
		LinearLayout view = (LinearLayout) getChildAt(getChildCount() - 1);
		LinearLayout linear_child = (LinearLayout) view.getChildAt(view
				.getChildCount() - 1);
		RelativeLayout footView = (RelativeLayout) linear_child
				.getChildAt(linear_child.getChildCount() - 1);
		int d = view.getBottom();
		int footerHeight = footView.getHeight();
		int scrollY = getScrollY();
		if (scrollY > d - getHeight() - footerHeight
				&& scrollY <= d - getHeight()) {// 此处表示ScrollView滑动到底部
			if (!noMore && onScrollToBottomListener != null)
				onScrollToBottomListener.onScrollToBottom();
		} else
			super.onScrollChanged(l, t, oldl, oldt);
	}

	public void setOnScrollToBottomListener(
			OnScrollToBottomListener onScrollToBottomListener) {
		this.onScrollToBottomListener = onScrollToBottomListener;
	}

	public void setNoMore(boolean noMore) {
		this.noMore = noMore;
	}

	public interface OnScrollToBottomListener {
		public void onScrollToBottom();

		public void onScroll(int scrollY);
	}
}
